package com.learning.servlet3x.context;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;
import java.util.EnumSet;

/**
 * ClassName: DynamicListener
 * Description: ServletContext 动态部署Servlet、过滤器、监听器
 * 1、这个功能放在两个地方
 * 1） ServletContextListener 的 contextInitialized 方法中调用
 * 2) 在 ServletContainerInitializer 的 onStartup() 方法中调用
 * <p>
 * Date: 2014/12/06  22:07 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@WebListener
public class DynamicListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        System.out.println("ServletContext 动态部署Servlet、过滤器、监听器： ServletContextListener");

        ServletContext servletContext = sce.getServletContext();

        // 动态添加 Filter
        FilterRegistration.Dynamic registration = servletContext.addFilter("DynamicFilter", DynamicFilter.class);
        registration.setAsyncSupported(isAsyncSupported());
        registration.addMappingForUrlPatterns(getDispatcherTypes(), false, "/dynamic/*");

        // 动态添加 Servlet
        ServletRegistration.Dynamic servlet = servletContext.addServlet("DynamicServlet", new DynamicServlet());
        servlet.addMapping("/dynamic/dynamicServlet");
        servlet.setLoadOnStartup(1);
        servlet.setInitParameter("user", "sam");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    private boolean isAsyncSupported() {
        return true;
    }

    private EnumSet<DispatcherType> getDispatcherTypes() {
        return isAsyncSupported() ?
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC) :
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE);
    }
}
